package com.csdn.leon.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import com.csdn.leon.activity.BlogHostActivity.ParserTask;
import com.csdn.leon.adapter.CloumnAdapter;
import com.csdn.leon.adapter.CloumnDetailAdapter;
import com.csdn.leon.base.BaseActivity;
import com.csdn.leon.db.DBUtil;
import com.csdn.leon.model.BlogModel;
import com.csdn.leon.model.CloumnModel;
import com.csdn.leon.model.ClumnsHost;
import com.csdn.leon.model.CommonList;
import com.csdn.leon.model.Person;
import com.csdn.leon.net.CSDNapi;
import com.csdn.leon.util.Constants;
import com.csdn.leon.util.JsoupUtil;
import com.csdn.leon.util.ListHelpUtil;
import com.csdn.leon.util.SPUtils;
import com.csdn.leon.util.URLUtil;
import com.csdn.leon.view.dialog.CustomDialog;
import com.csdn.leon.view.dialog.DialogHelper;
import com.csdn.leon.view.dialog.CustomDialog.DialogListener;
import com.csdn.leon.view.swipyrefreshlayout.SwipyRefreshLayout;
import com.csdn.leon.view.swipyrefreshlayout.SwipyRefreshLayoutDirection;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.csdn.leon.base.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class BlogCloumnDetailActivity extends BaseActivity implements
		SwipyRefreshLayout.OnRefreshListener, OnClickListener,
		OnItemClickListener {
	private static final String TAG = BlogHostActivity.class.getSimpleName();
	private ListView mListView;
	private SwipyRefreshLayout mSwipyRefreshLayout;
	private TextView leftTv;
	private ImageView leftImg;
	private TextView middleTv;
	private ImageView host_img;
	private TextView host_number;
	private TextView host_name;
	private Button host_watch;
	private String url;
	private String cloumnLink;
	private String username;
	protected int mCurrentPage = 1;
	private ParserTask mParserTask;
	private List<BlogModel> list;
	private ClumnsHost host;
	private View headView;
	private LayoutInflater inflater;
	private CloumnDetailAdapter cloumnAdapter;
	private DisplayImageOptions options;

	@SuppressLint("ResourceAsColor")
	private Handler hostHandle = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			host_watch.setVisibility(View.VISIBLE);
			if (msg.what == 0) {
				host_watch
						.setBackgroundResource(R.drawable.comment_bg_selected);
				host_watch.setTextColor(R.color.white);
				host_watch.setText("正在关注");
			} else if (msg.what == 1) {
				host_watch
						.setBackgroundResource(R.drawable.comment_bg_selector);
				host_watch.setTextColor(R.color.btn_bg_color);
				host_watch.setText("添加关注");

			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_cloumndetail_layout);
		inflater = LayoutInflater.from(this);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.csdn)
				.showImageForEmptyUri(R.drawable.csdn)
				.showImageOnFail(R.drawable.csdn).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(100)).build();
		initLayout();
		// Intent intent1 = new Intent(); //Itent就是我们要发送的内容
		// intent1.setAction("COM.DIALOG.SEARCH");
		// //设置你这个广播的action，只有和这个action一样的接受者才能接受者才能接收广播
		// sendBroadcast(intent1); //发送广播
	}

	private void initLayout() {
		cloumnLink = this.getIntent().getExtras().getString("clumnLink");
		mListView = (ListView) findViewById(R.id.listview_cloumn);
		headView = inflater.inflate(R.layout.host_head_layout, null);
		host_number = (TextView) headView.findViewById(R.id.host_number);
		host_name = (TextView) headView.findViewById(R.id.host_username_tv);
		host_watch = (Button) headView.findViewById(R.id.host_watch);

		host_watch.setOnClickListener(this);
		mListView.addHeaderView(headView);
		cloumnAdapter = new CloumnDetailAdapter(this);
		mListView.setAdapter(cloumnAdapter);
		mListView.setOnItemClickListener(this);
		mSwipyRefreshLayout = (SwipyRefreshLayout) findViewById(R.id.swipyrefreshlayout_cloumn);
		mSwipyRefreshLayout.setOnRefreshListener(this);
		leftTv = (TextView) findViewById(R.id.title_left_text);
		leftTv.setVisibility(View.GONE);
		leftImg = (ImageView) findViewById(R.id.title_left_img);
		leftImg.setVisibility(View.VISIBLE);
		leftImg.setImageResource(R.drawable.actionbar_back_icon_normal);
		leftImg.setOnClickListener(this);
		middleTv = (TextView) findViewById(R.id.title_middle_text);
		middleTv.setVisibility(View.VISIBLE);
		host_img = (ImageView) headView.findViewById(R.id.host_user_img);

		middleTv.setText(this.getResources().getText(
				R.string.title_middleleft_7));

		requestData(true);
	}

	// 发送请求的handle
	TextHttpResponseHandler handle = new TextHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2,
				Throwable arg3) {
			hideWaitDialog();
			mSwipyRefreshLayout.setRefreshing(false);
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String s) {
			Log.w(TAG, s);
			executeParserTask(s);
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_img:
			finish();
			break;
		case R.id.host_watch:
			// if (DBUtil.queryHost(BlogCloumnDetailActivity.this,
			// person.getUsername())) {
			// final CustomDialog dialog = DialogHelper
			// .getCustomDialog(BlogCloumnDetailActivity.this);
			// dialog.show();
			// dialog.setDialogListener(new DialogListener() {
			//
			// @Override
			// public void isCancel(boolean flag) {
			// dialog.hide();
			// if (flag) {
			// if (DBUtil.deleteHost(
			// BlogCloumnDetailActivity.this, username)) {
			// Message msg = new Message();
			// msg.what = 1;
			// hostHandle.sendMessage(msg);
			// }
			// } else {
			// }
			// }
			// });
			// } else {
			// if (DBUtil.insertHost(BlogCloumnDetailActivity.this, person)) {
			// Message msg = new Message();
			// msg.what = 0;
			// hostHandle.sendMessage(msg);
			// } else {
			// Toast.makeText(BlogCloumnDetailActivity.this, "关注失败", 1000)
			// .show();
			// }
			// }
			// break;
		}
	}

	/**
	 * Called when the
	 * {@link com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout}
	 * is in refresh mode. Just for example purpose.
	 */
	@Override
	public void onRefresh(SwipyRefreshLayoutDirection direction) {

		if (direction == SwipyRefreshLayoutDirection.TOP) {
			mCurrentPage = 1;
			sendRequestData(username, true);
		} else if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
			mCurrentPage++;
			sendRequestData(username, false);
		}
	}

	/***
	 * 获取列表数据
	 * 
	 * 
	 * @author leon
	 * 
	 * @return void
	 * @param refresh
	 */
	// 取新的数据
	protected void requestData(boolean refresh) {
		showWaitDialog();
		sendRequestData(username, refresh);
	}

	protected void sendRequestData(String username, boolean flag) {
		if (flag) {
			url = cloumnLink;
		} else {
			url = cloumnLink + "?&page=" + mCurrentPage;
		}
		CSDNapi.getBlogList(url, handle);
	}

	private void executeParserTask(String data) {
		cancelParserTask();
		mParserTask = new ParserTask(data);
		mParserTask.execute();
	}

	private void cancelParserTask() {
		if (mParserTask != null) {
			mParserTask.cancel(true);
			mParserTask = null;
		}
	}

	class ParserTask extends AsyncTask<Void, Void, String> {
		private final String reponseData;
		private boolean parserError;
		private List<CloumnModel> list;

		public ParserTask(String data) {
			this.reponseData = data;
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				CommonList<CloumnModel> commonList = ListHelpUtil
						.paraseCloumnModelToList(reponseData);
				list = (List<CloumnModel>) JsoupUtil
						.getCloumnsList(reponseData).get("cloumn");
				host = (ClumnsHost) JsoupUtil.getCloumnsList(reponseData).get(
						"host");

				// if (DBUtil.queryHost(BlogCloumnDetailActivity.this,
				// person.getUsername())) {
				// Message msg = new Message();
				// msg.what = 0;
				// hostHandle.sendMessage(msg);
				// } else {
				// Message msg = new Message();
				// msg.what = 1;
				// hostHandle.sendMessage(msg);
				// }
			} catch (Exception e) {
				e.printStackTrace();
				parserError = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			executeAdapterData(list);
		}
	}

	private void executeAdapterData(List<CloumnModel> list) {
		mSwipyRefreshLayout.setRefreshing(false);
		if (list != null) {
			if (mCurrentPage == 1) {
				cloumnAdapter.setList(list);
			} else {
				cloumnAdapter.addAllList(list);
			}
		} else {
			list = new ArrayList<CloumnModel>();
			cloumnAdapter.setList(list);
		}
		if((boolean) SPUtils.get(BlogCloumnDetailActivity.this, Constants.KEY_LOAD_IMAGE, true)){
		ImageLoader.getInstance().displayImage(host.getClumnImageUrl(),
				host_img, options);
		}
		host_name.setText(host.getClumnName());
		if (host_watch.isEnabled()) {
			host_watch.setEnabled(true);
		}
		hideWaitDialog();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		 CloumnModel blogModel = cloumnAdapter.getList().get(position);
		 Intent intent = new Intent(this, BlogContentActivity.class);
		 String url = blogModel.getLink();
		 intent.putExtra("blog_url", blogModel.getLink());
		 startActivity(intent);

	}
}
